from rest_framework import serializers
from .models import Portfolio, PortfolioHolding, StopLossSetting, Transaction
from products.models import Product
from users.models import User


class PortfolioSerializer(serializers.ModelSerializer):
    """投资组合序列化器"""
    
    class Meta:
        model = Portfolio
        fields = '__all__'
        read_only_fields = ('user', 'created_at', 'updated_at')
    
    def to_representation(self, instance):
        """自定义序列化表示，处理可能的decimal错误"""
        try:
            return super().to_representation(instance)
        except Exception as e:
            # 如果序列化失败，返回安全的默认值
            from decimal import Decimal
            data = {
                'id': instance.id,
                'name': instance.name,
                'description': instance.description,
                'stable_ratio': getattr(instance, 'stable_ratio', Decimal('0.0000')),
                'balanced_ratio': getattr(instance, 'balanced_ratio', Decimal('0.0000')),
                'growth_ratio': getattr(instance, 'growth_ratio', Decimal('0.0000')),
                'aggressive_ratio': getattr(instance, 'aggressive_ratio', Decimal('0.0000')),
                'total_amount': getattr(instance, 'total_amount', Decimal('0.00')),
                'current_value': getattr(instance, 'current_value', Decimal('0.00')),
                'status': instance.status,
                'created_at': instance.created_at,
                'updated_at': instance.updated_at,
                'user': instance.user.id if instance.user else None,
            }
            return data


class PortfolioHoldingSerializer(serializers.ModelSerializer):
    """投资组合持仓序列化器"""
    product_name = serializers.CharField(source='product.name', read_only=True)
    product_code = serializers.CharField(source='product.code', read_only=True)
    profit_loss = serializers.DecimalField(max_digits=15, decimal_places=2, read_only=True)
    profit_loss_rate = serializers.DecimalField(max_digits=10, decimal_places=4, read_only=True)
    
    class Meta:
        model = PortfolioHolding
        fields = '__all__'
        read_only_fields = ('portfolio', 'created_at', 'updated_at')
    
    def to_representation(self, instance):
        """自定义序列化表示，处理可能的decimal错误"""
        try:
            return super().to_representation(instance)
        except Exception as e:
            # 如果序列化失败，返回安全的默认值
            from decimal import Decimal
            return {
                'id': instance.id if hasattr(instance, 'id') else None,
                'portfolio': instance.portfolio.id if hasattr(instance, 'portfolio') else None,
                'product': instance.product.id if hasattr(instance, 'product') else None,
                'product_name': getattr(instance.product, 'name', '') if hasattr(instance, 'product') else '',
                'product_code': getattr(instance.product, 'code', '') if hasattr(instance, 'product') else '',
                'shares': Decimal('0'),
                'cost_price': Decimal('0'),
                'current_price': Decimal('0'),
                'cost_amount': Decimal('0'),
                'current_amount': Decimal('0'),
                'profit_loss': Decimal('0'),
                'profit_loss_rate': Decimal('0'),
                'purchase_date': getattr(instance, 'purchase_date', None),
                'updated_at': getattr(instance, 'updated_at', None),
            }


class StopLossSettingSerializer(serializers.ModelSerializer):
    """止损设置序列化器"""
    
    class Meta:
        model = StopLossSetting
        fields = '__all__'
        read_only_fields = ('portfolio', 'created_at', 'updated_at')
    
    def validate(self, data):
        """验证止损设置"""
        stop_loss_type = data.get('stop_loss_type')
        
        if stop_loss_type == 'fixed' and not data.get('fixed_percentage'):
            raise serializers.ValidationError("固定比例止损需要设置止损比例")
        
        if stop_loss_type == 'trailing' and not data.get('trailing_percentage'):
            raise serializers.ValidationError("移动止损需要设置移动比例")
        
        if stop_loss_type == 'technical' and not data.get('technical_indicator'):
            raise serializers.ValidationError("技术指标止损需要设置技术指标")
        
        return data


class TransactionSerializer(serializers.ModelSerializer):
    """交易记录序列化器"""
    product_name = serializers.CharField(source='product.name', read_only=True)
    product_code = serializers.CharField(source='product.code', read_only=True)
    
    class Meta:
        model = Transaction
        fields = '__all__'
        read_only_fields = ('portfolio', 'created_at')


class PortfolioDetailSerializer(serializers.ModelSerializer):
    """投资组合详情序列化器"""
    holdings = PortfolioHoldingSerializer(many=True, read_only=True)
    stop_loss_settings = StopLossSettingSerializer(many=True, read_only=True)
    recent_transactions = TransactionSerializer(many=True, read_only=True)
    
    class Meta:
        model = Portfolio
        fields = '__all__'
        read_only_fields = ('user', 'created_at', 'updated_at')


class PortfolioCreateSerializer(serializers.ModelSerializer):
    """投资组合创建序列化器"""
    
    class Meta:
        model = Portfolio
        fields = ('name', 'description', 'total_amount')
    
    def create(self, validated_data):
        """创建投资组合"""
        user = self.context['request'].user
        validated_data['user'] = user
        return super().create(validated_data)


class AssetAllocationSerializer(serializers.Serializer):
    """资产配置序列化器"""
    total_amount = serializers.DecimalField(max_digits=15, decimal_places=2)
    risk_level = serializers.ChoiceField(choices=[
        (1, '保守型'),
        (2, '稳健型'),
        (3, '平衡型'),
        (4, '成长型'),
        (5, '激进型')
    ])
    
    def validate_total_amount(self, value):
        """验证投资金额"""
        if value <= 0:
            raise serializers.ValidationError("投资金额必须大于0")
        return value


class RebalanceSerializer(serializers.Serializer):
    """再平衡序列化器"""
    portfolio_id = serializers.IntegerField()
    rebalance_type = serializers.ChoiceField(choices=[
        ('time', '定期再平衡'),
        ('threshold', '阈值再平衡'),
        ('manual', '手动再平衡')
    ])
    
    def validate_portfolio_id(self, value):
        """验证投资组合ID"""
        try:
            portfolio = Portfolio.objects.get(id=value)
            if portfolio.user != self.context['request'].user:
                raise serializers.ValidationError("无权限操作此投资组合")
        except Portfolio.DoesNotExist:
            raise serializers.ValidationError("投资组合不存在")
        return value